#!/usr/bin/env python

# #############################################################################
# Tex Editor
#
# --
#    Author: David Aguilera
#       Created: 13/03/2011
#       Last modified: 04/05/2011
# 
#  Acknowledgements:
#    Based on Ryan Paul's (SegPhault) work
#    http://bit.ly/bLSI6
# 
# #############################################################################

APP_NAME = "exsited"

import gtk, webkit, sys
import os, os.path
import gettext
gettext.bindtextdomain(APP_NAME)
gettext.textdomain(APP_NAME)
_ = gettext.gettext

from exsited.documents import Article

class TexEditor(gtk.Window):

  def __init__(self, filename=None):
    gtk.Window.__init__(self)
    self.set_title("Exsited!")
    self.connect("delete_event", self.on_quit)
    self.resize(800, 550)


    self.document = None
    self.editor = webkit.WebView()
    try:
      if os.path.exists(filename):
        self.open_file(filename)
      else:
        raise Exception
    except:
       self.on_new(None)

    scroll = gtk.ScrolledWindow()
    scroll.add(self.editor)
    scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)

    self.ui = self.generate_ui()
    self.menubar = self.ui.get_widget("/menubar_main")
    self.toolbar1 = self.ui.get_widget("/toolbar_main")

    self.layout = gtk.VBox()
    self.layout.pack_start(self.menubar, False)
    self.layout.pack_start(self.toolbar1, False)
    self.layout.pack_start(scroll, True, True)
    self.add(self.layout)


  def generate_ui(self):
    ui_def = """
    <ui>
      <menubar name="menubar_main">
        <menu action="menuFile">
          <menuitem action="new" />
          <menuitem action="open" />
          <menuitem action="save" />
        </menu>
      </menubar>
      <toolbar name="toolbar_main">
        <toolitem action="new" />
        <toolitem action="open" />
        <toolitem action="save" />
        <separator />
        <toolitem action="undo" />
        <toolitem action="redo" />
        <separator />
        <toolitem action="cut" />
        <toolitem action="copy" />
        <toolitem action="paste" />
      </toolbar>
    </ui>
    """

    actions = gtk.ActionGroup("Actions")
    actions.add_actions([
      ("menuFile", None, "_File"),

      ("new", gtk.STOCK_NEW, "_New", None, None, self.on_new),
      ("open", gtk.STOCK_OPEN, "_Open", None, None, self.on_open),
      ("save", gtk.STOCK_SAVE, "_Save", None, None, self.on_save),

      ("undo", gtk.STOCK_UNDO, "_Undo", None, None, self.on_action),
      ("redo", gtk.STOCK_REDO, "_Redo", None, None, self.on_action),

      ("cut", gtk.STOCK_CUT, "_Cut", None, None, self.on_action),
      ("copy", gtk.STOCK_COPY, "_Copy", None, None, self.on_action),
      ("paste", gtk.STOCK_PASTE, "_Paste", None, None, self.on_paste),
    ])

    
    for n in ["undo", "redo", "cut", "copy", "paste"]:
       actions.get_action(n).set_sensitive(False)

    ui = gtk.UIManager()
    ui.insert_action_group(actions)
    ui.add_ui_from_string(ui_def)

    return ui


  def on_quit(self, action, event):
    # Remove temporary files
    if not self.document == None:
       if self.document.close():
          self.document.destroy()
       else:
          return True

    gtk.main_quit()
    return False

  def on_action(self, action):
    self.editor.execute_script("document.execCommand('%s', false, false);" % action.get_name())

  def on_paste(self, action):
    self.editor.paste_clipboard()

  def on_new(self, action):
    self.open_file(None)

  def open_file(self, filename):
    try:
       if not self.document == None:
          if self.document.close():
             self.document.destroy()
          else:
             return

       self.document = Article(filename)
       self.editor.load_uri('file://' + self.document.get_html_location())

    except:
       html = "There was an error while opening <code>%s</code>." % (filename)
       self.editor.load_html_string(html, "file://" + os.getcwd())

  def on_open(self, action):
    dialog = gtk.FileChooserDialog("Select a TeX file", self, gtk.FILE_CHOOSER_ACTION_OPEN,
      (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))

    filter = gtk.FileFilter()
    filter.set_name("All files")
    filter.add_pattern("*.tex")
    filter.add_pattern("*.x8d")
    dialog.add_filter(filter)

    filter = gtk.FileFilter()
    filter.set_name("TeX files")
    filter.add_pattern("*.tex")
    dialog.add_filter(filter)

    filter = gtk.FileFilter()
    filter.set_name("Exsited! files")
    filter.add_pattern("*.x8d")
    dialog.add_filter(filter)

    if dialog.run() == gtk.RESPONSE_OK:
      fn = dialog.get_filename()
      if os.path.exists(fn):
        self.open_file(fn)
    dialog.destroy()

  def on_save(self, action):
     pass
#    dest = "/tmp/checkme.html"
#    if dest:
#      with open(dest, 'w+') as fd: fd.write(self.get_html())
#    else:
#      dialog = gtk.FileChooserDialog("Select an HTML file", self, gtk.FILE_CHOOSER_ACTION_SAVE,
#        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
#
#      if dialog.run() == gtk.RESPONSE_OK:
#        dest = dialog.get_filename()
#        with open(dest, "w+") as fd: fd.write(self.get_html())
#      dialog.destroy()
#
#  def get_html(self):
#    self.editor.execute_script("document.title=document.documentElement.innerHTML;")
#    return self.editor.get_main_frame().get_title()


fn = None
try:
   fn = sys.argv[1]
except:
   pass

e = TexEditor(filename=fn)
e.show_all()
gtk.main()

